package com.example.practice.sys.service.impl;


import com.example.practice.pojo.Detials;
import com.example.practice.pojo.Dict;
import com.example.practice.sys.mapper.DictMapper;
import com.example.practice.sys.service.DictService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DictServiceImpl implements DictService {

    @Resource
    private DictMapper dictMapper;





    // 添加字典的业务层逻辑
    @Override
    public int insertDict(Dict dict) throws Exception {
        // 1. 检查字典名称是否已存在
        Dict existingDict = dictMapper.findDict(dict.getDname());

        // 2. 如果存在则返回-1
        if (existingDict != null) {
            return -1;
        }
        // 3. 设置默认状态为启用(0)
        if (dict.getDstate()!=0) {
            dict.setDstate(0);
        }
        // 4. 插入字典
        int affectedRows = dictMapper.addDict(dict);
        // 5. 返回插入后的ID (通过keyProperty自动回填到dict对象)
        return affectedRows > 0 ? (int) dict.getId() : -1;
    }



    /**
     * 分页查询数据
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Dict> findDictByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Dict> dictList = dictMapper.findAllDicts(); // 只查分页数据
        return new PageInfo<>(dictList); // 返回完整分页信息
    }

    @Override
    public int updateDict(Dict dict) throws Exception {
        return   dictMapper.updateDictById( dict);
    }

    @Override
    public Dict findDictById(Integer id) throws Exception {
        if (id == null) {
            return null;
        }
        return dictMapper.findDictById(id);
    }

    @Override
    public int deleteDictById(int id) throws Exception {

        Dict dict= dictMapper.findDictById(id);
        // 数据不存在 , 或者已经删除
        if (null ==dict || dict.getIsDel()== 1) {return  -1 ;}
        // 数据存在, 修改标志位
        dict.setIsDel(1);
        return dictMapper.updateDictById( dict);
    }

    @Override
    public List<Detials> findAllDetails(Dict dict ) throws Exception{
        return dictMapper.findDetials(dict.getDname());
    }
}
